package com.example.recipes;

import org.apache.curator.framework.CuratorFramework;
import org.apache.curator.framework.recipes.leader.LeaderSelector;
import org.apache.curator.framework.recipes.leader.LeaderSelectorListenerAdapter;

import java.util.concurrent.TimeUnit;

/**
 * @author Creared by wangyang on 2019-01-29 11:14
 * email:techyang.wangy.@ymm56.com
 */
public class MasterSelector {

    private static CuratorFramework client = CuratorFrameworkHolder.CURATOR_FRAMEWORK;

    private static final String MASTER_SELECTOR_PATH = "/zk-book/masterSelector";

    public static void main(String[] args) throws InterruptedException {
        client.start();
        LeaderSelector ls = new LeaderSelector(client, MASTER_SELECTOR_PATH, new LeaderSelectorListenerAdapter() {
            @Override
            public void takeLeadership(CuratorFramework client) throws Exception {
                System.out.println("当选为 master 角色");
                TimeUnit.SECONDS.sleep(3);
                System.out.println("释放 master 角色");
            }
        });
        ls.autoRequeue();
        ls.start();
        TimeUnit.SECONDS.sleep(Integer.MAX_VALUE);
    }
}
